<?php
$ROOT_DIR_PATH = '../';
require_once($ROOT_DIR_PATH . 'includes/includes.php');
require_once($ROOT_DIR_PATH . 'classes/class.user.inc.php');
require_once($ROOT_DIR_PATH . 'classes/class.dealersgroup.inc.php');
$ADMIN_PAGE_TITLE = 'Dealer Page';
$listingUrl = $ADMIN_BASE_HREF . "userlisting.php";
$dashBoardUrl = $ADMIN_BASE_HREF . "dashboard.php";
$password = '';
$repeatpassword = '';
$currentEmail = '';
$dealerGroupIdArray = Array();


$loginUrl = $ADMIN_BASE_HREF . "login.php";
if (!$GENOBJ->isLoggedIn()) {
    $GENOBJ->redirect($loginUrl);
}

if(!$GENOBJ->isAdminLogin()) {
	$GENOBJ->redirect($dashBoardUrl);
}

$GENOBJ->clearSessionErrorMessages();
$mode = 'insert';
$userObj = new user();
$dealersGroupObj = new dealersgroup();
$dealerGroup = $dealersGroupObj->getAllDealersgroupList('id,groupname' , 'where status = "1"');



if (isset($_GET['id'])) {
    if ((trim($_GET['id']) == '')) {
	$GENOBJ->redirect($listingUrl);
	exit;
    }
    $userObj->setuserid($_GET['id']);
    $mode = 'edit';
	
	if (isset($_GET['mode'])) {
		if ((trim($_GET['mode']) == 'delete')) {
			$deleteId = $_GET['id'];
			$deleteId = $GENOBJ->filter($deleteId, Array("utfencode", "TrimElement", "htmlEntity"));
			$userObj->delete($deleteId);
			$_SESSION['error']['user-updated'] = 'Dealer deleted successfully';
			$GENOBJ->redirect($listingUrl);
			exit;
		}				if ((trim($_GET['mode']) == 'status')) {			$updateId = $_GET['id'];			$type = $_GET['type'];			$type = $GENOBJ->filter($type, Array("utfencode", "TrimElement", "htmlEntity"));			$updateId = $GENOBJ->filter($updateId, Array("utfencode", "TrimElement", "htmlEntity"));			$statusType = ($type == 'active')?"Inactive":"Active";			$updateSql = "UPDATE `user` SET `status` = '".$statusType."' WHERE `user`.`userid` =".$updateId;			$result = $DBOBJ->sql_query($updateSql);			$_SESSION['error']['user-updated'] = 'Dealer Status updated successfully';			$GENOBJ->redirect($listingUrl);			exit;		}				
    }
	
}

if (isset($_POST['id'])) {
    if (trim($_POST['id']) != '') {
	$userObj->setuserid($_POST['id']);
	$mode = 'edit';
    }
}

if ($mode == 'edit') {
    $id = $userObj->getuserid();
    $userData = $userObj->select($id);
    $password = $userData['password'];
    $currentEmail = $userData['email'];
	$dealerGroupIds = $userData['dealergroup'];
	$dealerGroupIdArray = explode(",",$dealerGroupIds);
	
    $filterArray = Array("utfdecode"); //Utf change
    $userData = $GENOBJ->filter($userData, $filterArray); //Utf change
    $userObj->setAll($userData);
		
	//Validation to prevent editing of the Admin user	
	 if ($id == '0') {
		$GENOBJ->redirect($listingUrl);
	 }
}


$errorMessageArray = Array();
if ($_POST) {
    $filterElements = Array();
    $filterArray = Array("utfencode", "TrimElement", "htmlEntity");  //Utf change
    $repeatpassword = $_POST['repeatpassword'];
    $repeatpassword = $GENOBJ->filter($repeatpassword, $filterArray);
    $filterElements['id'] = $_POST['id'];
    $filterElements['username'] = $_POST['username'];
    $filterElements['password'] = $_POST['password'];
    $filterElements['firstname'] = $_POST['firstname'];
    $filterElements['lastname'] = $_POST['lastname'];
	
    $filterElements['email'] = $_POST['email'];
	$filterElements['phone'] = $_POST['phone'];
	$filterElements['mobile'] = $_POST['mobile'];
	$filterElements['shippingaddress'] = $_POST['shippingaddress'];
	$filterElements['billingaddress'] = $_POST['billingaddress'];
	$filterElements['isadmin'] = $_POST['isadmin'];
    $filterElements['status'] = $_POST['status'];
    $filterElements = $GENOBJ->filter($filterElements, $filterArray);
    $userObj->setAll($filterElements);
	
	
    if ($GENOBJ->IsEmpty($userObj->getusername())) {
	$errorMessageArray[] = 'Please enter dealers profile name.';
    }

    if ($GENOBJ->IsEmpty($userObj->getfirstname())) {
	$errorMessageArray[] = 'Please enter first name.';
    }

    if ($GENOBJ->IsEmpty($userObj->getlastname())) {
	$errorMessageArray[] = 'Please enter last name.';
    }
	
	
	if (isset($_POST['dealergroup'])) {
		$dealerGroupIdArray = $_POST['dealergroup'];
	} else {
		$errorMessageArray[] = 'Please choose dealers group.';
	}
	
    if ($GENOBJ->IsEmpty($userObj->getemail())) {
	$errorMessageArray[] = 'Please enter email.';
    } else {
	if (!$GENOBJ->ValidEmailAddress($userObj->getemail())) {
	    $errorMessageArray[] = 'Email address is not valid';
	}
    }

	
    if ($mode == 'insert') {
	if ($GENOBJ->IsEmpty($userObj->getpassword())) {
	    $errorMessageArray[] = "Password should not be blank.";
	} else {
	    if (!$GENOBJ->ValidatePassword($userObj->getpassword())) {
		$errorMessageArray[] = "Password should contain more than 5 characters.";
	    }
	}

	if ($userObj->getpassword() != $repeatpassword) {
	    $errorMessageArray[] = "Password and Repeat password doesnot match.";
	}
    } else {
	if (!$GENOBJ->IsEmpty($userObj->getpassword())) {
	    if (!$GENOBJ->ValidatePassword($userObj->getpassword())) {
		$errorMessageArray[] = "Password should contain more than 5 characters.";
	    }
	    if ($userObj->getpassword() != $repeatpassword) {
		$errorMessageArray[] = "Password and Repeat password doesnot match.";
	    }
	} else {
	    $userObj->setpassword($password);
	}
    }

    if ($GENOBJ->IsEmpty($userObj->getstatus())) {
	$errorMessageArray[] = 'Please select status.';
    }
	
    if (count($errorMessageArray) <= 0) {
	if ($mode == 'insert') {
	    $userExist = $userObj->checkEmailExists($userObj->getemail());
	    if ($userExist) {
		$errorMessageArray[] = 'Email-Address already exist';
	    }
	} else {
	    $userExist = $userObj->checkEmail($currentEmail, $userObj->getemail());
	    if (!$userExist) {
		$errorMessageArray[] = 'Email-Address already exist';
	    }
	    if (!$GENOBJ->IsEmpty($userObj->getpassword())) {
		
	    }
	}
    }

    if (count($errorMessageArray) <= 0) {
	if ($mode == 'insert') {
		$userObj->setdealergroup(implode(",",$_POST['dealergroup']));
	    $password = base64_encode($userObj->getpassword());
	    $userObj->setpassword($password);
		$userObj->setcreateddate(date('Y-m-d H:i:s'));
	    $insertid = $userObj->insert();

	    if ($insertid > 0) {
		$_SESSION['error']['user-inserted'] = 'Dealer Added successfully';
		$GENOBJ->redirect($listingUrl);
	    } else {
		$_SESSION['error']['user-error'] = 'Error in insertion . Please try again!';
		$GENOBJ->redirect($listingUrl);
	    }
	} else {
		$userObj->setdealergroup(implode(",",$_POST['dealergroup']));
	    if ( trim( $_POST['password'] ) != '' ) {
			$password = base64_encode($userObj->getpassword());
			$userObj->setpassword($password);
	    }
	    $userObj->update($id);
	    $_SESSION['error']['user-updated'] = 'Dealer updated successfully';
	    $GENOBJ->redirect($listingUrl);
	}
    }
}
?>
<?php include('templates/header.php'); ?>
<body>
    <div id="user"></div>
    <div id="ncleangrey-container">
        <?php include('templates/navigation.php'); ?>
        <div class="breadcrumbs">
            <div id="nav-icons_all">
                <ul id="nav-icons">
                    <li class="logout-icon"><a  title="Logout"  href="logout.php">Logout</a></li>
                </ul>
            </div>
            <p class="breadcrumbs">
                <a title="Home" href="dashboard.php">Home</a> &#187; <a title="user" href="userlisting.php">Dealer</a> &#187; <?php if ($mode == 'edit') { ?>Edit<?php } else { ?>Add<?php } ?> Dealer
            </p>
        </div>
        <div class="hstippled">&nbsp;</div>
        <div id="MainContent">
            <div>
                <div class="pageerrorcontainer-validator">
                    <div class="error-iterator"></div>
                </div>
            </div>
            <?php if (count($errorMessageArray) > 0): ?>
                <div class="pageerrorcontainer">
                <?php foreach ($errorMessageArray as $erroValue): ?>
                    <div class="pageoverflow">
                        <img src="images/icons/system/stop.gif" class="systemicon" alt="Error" title="Error" />
                        <label class="errorlabel"><?php echo $erroValue; ?></label>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endif; ?>
                    <div class="clearb">&nbsp;</div>
                    <div id="Edit_Content_Result"></div>
                    <div class="pagecontainer pageoverflow">
                        <div class="pageheader">
                    <?php if ($mode == 'edit') { ?>Edit<?php } else { ?>Add<?php } ?> Dealer
                    <div class="field-required">* Fields are required </div>
                </div>
                <div style="clear: both;"></div>
                <form method="post" enctype="multipart/form-data" action="user.php" name="userfrm" id="userfrm">
                    <input type="hidden" id="id" value="<?php echo $userObj->getuserid(); ?>" name="id">
		    
                    <div id="page_content">

			<div class="pageoverflow">
                            <div class="pagetext">Dealer profile Name<span class="error-star">*</span>:</div>
                            <div class="pageinput">
                                <input type="text" name="username" id="username" value="<?php echo $userObj->getusername(); ?>" size="60"/>
                            </div>
                        </div>
			
                        <div class="pageoverflow">
                            <div class="pagetext">First Name<span class="error-star">*</span>:</div>
                            <div class="pageinput">
                                <input type="text" name="firstname" id="firstname" value="<?php echo $userObj->getfirstname(); ?>" size="60"/>
                            </div>
                        </div>
			
                        <div class="pageoverflow">
                            <div class="pagetext">Last Name<span class="error-star">*</span>:</div>
                            <div class="pageinput">
                                <input type="text" name="lastname" id="lastname" value="<?php echo $userObj->getlastname(); ?>" size="60"/>
                            </div>
                        </div>
						
						
						<div class="pageoverflow">
							<div class="pagetext">Dealergroup<span class="error-star">*</span>:</div>
								<div class="pageinput">
								   <?php foreach($dealerGroup as $key => $value):?>
									<input type="checkbox" id="dealergroup_id_<?php echo $value['id'];?>" name="dealergroup[]" value="<?php echo $value['id'];?>"  <?php echo (in_array($value['id'],$dealerGroupIdArray))?"checked='checked'":""; ?>  />
									<label for="dealergroup_id_<?php echo $value['id'];?>"><?php echo $value['groupname'];?></label>
									<br/>
								   <?php endforeach;?>
								</div>
						</div>
						
						<?php /*?>
						<div class="pageoverflow">
							<div class="pagetext">Dealer's Group<span class="error-star">*</span>:</div>
							<div class="pageinput">
								<select name="dealergroup" id="dealergroup">
                                    <option value="">--Select Dealer Group--</option>
									<?php foreach($dealerGroup as $key => $value):?>
                                    <option value="<?php echo $value['id'];?>" <?php echo ($userObj->getdealergroup() == $value['id']) ? "selected" : ""; ?>><?php echo $value['groupname'];?></option>
									<?php endforeach;?>
								</select>
							</div>
						</div>
						<?php */?>
			
                        <div class="pageoverflow">
                            <div class="pagetext">Email<span class="error-star">*</span>:</div>
                            <div class="pageinput">
                                <input type="text" name="email" id="email" value="<?php echo $userObj->getemail(); ?>" size="60"/>
                            </div>
                        </div>
						
						<div class="pageoverflow">
                            <div class="pagetext">Phone:</div>
                            <div class="pageinput">
                                <input type="text" name="phone" id="phone" value="<?php echo $userObj->getphone(); ?>" size="60"/>
                            </div>
                        </div>
						
						<div class="pageoverflow">
                            <div class="pagetext">Mobile:</div>
                            <div class="pageinput">
                                <input type="text" name="mobile" id="mobile" value="<?php echo $userObj->getmobile(); ?>" size="60"/>
                            </div>
                        </div>
						
						<div class="pageoverflow">
                            <div class="pagetext">Shipping Address:</div>
                            <div class="pageinput">
								<textarea id="shippingaddress" name="shippingaddress" cols="50" rows="5"><?php echo $userObj->getshippingaddress(); ?></textarea>
                            </div>
                        </div>
						
						<div class="pageoverflow">
                            <div class="pagetext">Billing Address:</div>
                            <div class="pageinput">
								<textarea id="billingaddress" name="billingaddress" cols="50" rows="5"><?php echo $userObj->getbillingaddress(); ?></textarea>
                            </div>
                        </div>

						<div class="pageoverflow">
							<div class="pagetext">Password<span class="error-star">*</span>:</div>
							<div class="pageinput">
								<input type="password" name="password" id="password"  size="25" maxlength="15"/>
							</div>
						</div>

						<div class="pageoverflow">
							<div class="pagetext">Repeat Password<span class="error-star">*</span>:</div>
							<div class="pageinput">
								<input type="password" name="repeatpassword" id="repeatpassword" value=""  maxlength="15" size="25"/>
							</div>
						</div>
				
				
			<div class="pageoverflow">
				<div class="pagetext">Do you want to give this dealer Admin Access ?</div>
				<div class="pageinput">
					<input type="radio" id="isadmin_yes" name="isadmin" value="1" <?php echo ($userObj->getisadmin() == 1)?"checked='checked'":""; ?>/>
					<label for="isadmin_yes">Yes</label>
					&nbsp;&nbsp;&nbsp;&nbsp;
					<input type="radio" id="isadmin_no" name="isadmin" value="0" <?php echo ($userObj->getisadmin() == 0)?"checked='checked'":""; ?>/>
					<label for="isadmin_no">No</label>
				</div>
			</div>
				
			<div class="pageoverflow">
                            <div class="pagetext">Status<span class="error-star">*</span>:</div>
                            <div class="pageinput">
                                <select name="status" id="status">
                                    <option value="">--Select Status--</option>
                                    <option value="Active" <?php echo ($userObj->getstatus() == 'Active') ? 'selected' : ''; ?> >Active</option>
                                    <option value="Inactive" <?php echo ($userObj->getstatus() == 'Inactive') ? 'selected' : ''; ?>>Inactive</option>
                                </select>
                            </div>
                        </div>
			
                        <div class="pageoverflow">
                            <p class="pagetext">&nbsp;</p>
                            <p class="pageinput">
                                <input type="submit" name="submitbutton" value="Submit"  title="Save changes" />
                                <input type="reset" name="apply" value="Reset" title="Save changes and continue to edit" />
                            </p>
                        </div>
                        <div style="clear: both;">&nbsp;</div>
                    </div>
                </form>
            </div>
            <p class="pageback">
                <a class="pageback" href="userlisting.php">&#171; Back to Listing</a>
            </p>
            <div class="clearb"></div>
        </div>
    </div>
<?php include('templates/footer.php'); ?>
</body>
</html>